/**
 * @author jason61719
 * @buildTime 2011.03.12
 * @description 本类用于连接缓冲池Memcached
 */
package me.send.framework.util;

import java.util.Date;

import com.danga.MemCached.MemCachedClient;
import com.danga.MemCached.SockIOPool;

public class CacheHelper {
	
	/* 单例模式 */
	protected static MemCachedClient memCachedClient = new MemCachedClient();
	
	private CacheHelper() {

	}
	
	/* 配置服务器组 */
	static {
		
		/* 定义IP地址和端口 */
//		String[] servers = { "127.0.0.1:11212" };
		String[] servers = { "649ca313e7654dd5.m.jst.cnhzalicm10pub001jae001.ocs.aliyuncs.com:11212" };
		
		/* 设置缓存大小 */
		Integer[] weights = { 2 };
		
		/* 拿到一个连接池的实例 */
		SockIOPool pool = SockIOPool.getInstance();
		
		/* 注入服务器组信息 */
		pool.setServers(servers);
		pool.setWeights(weights);
		
		/* 配置缓冲池的一些基础信息 */
		pool.setInitConn(5);
		pool.setMinConn(5);
		pool.setMaxConn(250);
		pool.setMaxIdle(1000 * 60 * 60 * 6);
		
		/* 设置线程休眠时间 */
		pool.setMaintSleep(30);
		
		/* 设置关于TCP连接 */
		pool.setNagle(false);// 禁用nagle算法
		pool.setSocketConnectTO(0);
		pool.setSocketTO(3000);// 3秒超时
		
		/* 初始化 */
		pool.initialize();
		
		/* 设置缓存压缩 */
		memCachedClient.setCompressEnable(true);
		memCachedClient.setCompressThreshold(64 * 1024);
		
	}
	
	public static boolean delete(String arg0){
		return memCachedClient.delete(arg0);
	}
	
	public static boolean delete(String arg0,Date arg1){
		return memCachedClient.delete(arg0, arg1);
	}
	
	
	public static boolean replace(String arg0,Object arg1){
		return memCachedClient.replace(arg0, arg1);
	}
	
	public static boolean replace(String arg0,Object arg1,Date arg2){
		return memCachedClient.replace(arg0, arg1, arg2);
	}
	
	
	public static boolean set(String arg0, Object arg1,Date arg2){
		return memCachedClient.set(arg0, arg1, arg2);
	}
	
	public static boolean set(String arg0, Object arg1) {
		return memCachedClient.set(arg0, arg1);
	}
	
	public static Object get(String arg0) {
		return memCachedClient.get(arg0);
	}
	
	/* 测试 */
	public static void main(String[] args) {
		CacheHelper.set("gogo", "gogogogo");
		System.out.println(CacheHelper.get("gogo"));// gogogogo
		System.out.println(CacheHelper.get("gogog"));// null
		/* 如果出现都为null，检查地址和端口。端口可以到Memcached同目录配置文件看 */
	}
	
}

